﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using XChipTool.Enties;
using XChipTool.BusinessCore;

namespace XChipTool
{
    public partial class XChip_Polling : DevExpress.XtraEditors.XtraForm
    {

        public int isPress_key;

        private List<BinChoiceData> listC = new List<BinChoiceData>();
        polling_registerManager pollBll = new polling_registerManager();
        List<polling_register> polllist;
        public delegate void SendXChip_PollingClick(string isAdc);
        public event SendXChip_PollingClick SendPolling;

        public XChip_Polling()
        {
            InitializeComponent();
        }

        public XChip_Polling(int _isPress_key, List<BinChoiceData> _list)
        {
               isPress_key = _isPress_key;
               listC = _list;
               InitializeComponent();
        }

        private void XChip_Polling_Load(object sender, EventArgs e)
        {

            if ( null != listC)
            {
                cmb_Setting0.Properties.DataSource = listC;
                cmb_Setting1.Properties.DataSource = listC;
                cmb_Setting2.Properties.DataSource = listC;
                cmb_Setting3.Properties.DataSource = listC;

                cmb_gpoiSetting0.Properties.DataSource = listC;
                cmb_gpoiSetting1.Properties.DataSource = listC;
                cmb_gpoiSetting2.Properties.DataSource = listC;
                cmb_gpoiSetting3.Properties.DataSource = listC;

                gridControl1.DataSource = listC.Where(c => c.isDel == false).OrderBy(c => c.Sort);
            }

            if (isPress_key == 0)
            {
                navigationFrame1.SelectedPage = BtnPage;
                polllist =  pollBll.GetList();


            }
            else
            {
                navigationFrame1.SelectedPage = AdcPage;
                polllist = pollBll.GetList();
            }
            
        }

        private void textEdit2_EditValueChanged(object sender, EventArgs e)
        {
            //0x1443,0x08,// 	[ 7: 0]GPIO_Polling_One;

            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "1443")
                {
                    c.DefaultVal = Convert.ToUInt32(textEdit2.Text).ToString("X2");
                }
            });
        }

        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {
            //0x1444,0x09,// 	[ 7: 0]GPIO_Polling_Two;
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "1444")
                {
                    c.DefaultVal = Convert.ToUInt32(textEdit1.Text).ToString("X2");
                }
            });
        }

        private void statetxt0_EditValueChanged(object sender, EventArgs e)
        {
            //            0x141c,0xff,//     [ 7: 0]ASP_State_0_Adc_Value;
            //0x141d,0x03,//     [15: 8]ASP_State_0_Adc_Value;
            var str = (sender as TextEdit).Text.PadLeft(4, '0');
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "141c")
                {
                    c.DefaultVal = $"{str[2]}{str[3]}";
                }
                if (c.Addr.ToLower() == "141d")
                {
                    c.DefaultVal = $"{str[0]}{str[1]}";
                }
            });

        }

        private void statetxt1_EditValueChanged(object sender, EventArgs e)
        {
            //            0x141e,0xf9,//     [ 7: 0]ASP_State_1_Adc_Value;
            //0x141f,0x00,//     [15: 8]ASP_State_1_Adc_Value;
            var str = (sender as TextEdit).Text.PadLeft(4, '0');
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "141e")
                {
                    c.DefaultVal = $"{str[2]}{str[3]}";
                }
                if (c.Addr.ToLower() == "141f")
                {
                    c.DefaultVal = $"{str[0]}{str[1]}";
                }
            });
        }

        private void statetxt2_EditValueChanged(object sender, EventArgs e)
        {
            //            0x1420,0x05,//     [ 7: 0]ASP_State_2_Adc_Value;
            //0x1421,0x02,//     [15: 8]ASP_State_2_Adc_Value;
            var str = (sender as TextEdit).Text.PadLeft(4, '0');
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "1420")
                {
                    c.DefaultVal = $"{str[2]}{str[3]}";
                }
                if (c.Addr.ToLower() == "1421")
                {
                    c.DefaultVal = $"{str[0]}{str[1]}";
                }
            });
        }

        private void statetxt3_EditValueChanged(object sender, EventArgs e)
        {
            //            0x1422,0x6c,//     [ 7: 0]ASP_State_3_Adc_Value;
            //0x1423,0x00,//     [15: 8]ASP_State_3_Adc_Value;
            var str = (sender as TextEdit).Text.PadLeft(4, '0');
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "1422")
                {
                    c.DefaultVal = $"{str[2]}{str[3]}";
                }
                if (c.Addr.ToLower() == "1423")
                {
                    c.DefaultVal = $"{str[0]}{str[1]}";
                }
            });
        }

        private void Erangetxt_EditValueChanged(object sender, EventArgs e)
        {
            //0x1424,0x10,//     [ 7: 0]ASP_Adc_Range;//default:0x10
           
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "1424")
                {
                    c.DefaultVal =(sender as TextEdit).Text.PadLeft(2,'0');
                }
            });

        }

        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {

            //if (e.Page.Text == "ADC轮询")
            //{
            //    //0x13d6,0x01,// 	[ 7: 0]Setting_Polling_Enable;//
            //    //0x13d8,0x02,// 	[ 7: 0]Setting_Polling_Method;//0:press key   1: two gpio dial 
               
            //}

            //if (e.Page.Text == "双GPIO拨码")
            //{
            //    //0x13d6,0x01,// 	[ 7: 0]Setting_Polling_Enable;//
            //    //0x13d8,0x01,// 	[ 7: 0]Setting_Polling_Method;
               
            //}
          


        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            if (isPress_key == 0)
            {

                if (string.IsNullOrEmpty(Key_Down_Delay.Text)||string.IsNullOrEmpty(Key_Up_Delay.Text)|| string.IsNullOrEmpty(Scan_Key_Time.Text))
                {
                    XtraMessageBox.Show("文本框不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (cmb_Polling_Pin_Select.EditValue.ToString() == "ADC_IN") {
                    if (string.IsNullOrEmpty(ADC_Value.Text))
                    {
                        XtraMessageBox.Show("文本框不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }


                List<polling_register> pollTemp = new List<polling_register>();
                if (cmb_Polling_Pin_Select.EditValue.ToString() == "ADC_IN")
                {
                    pollTemp = polllist.Where(c => c.ADC_IN == 1).ToList();
                }
                if (cmb_Polling_Pin_Select.EditValue.ToString().Contains("GPIO")) {
                    pollTemp = polllist.Where(c => c.GPIO == 1).ToList();
                }
                var count =    listC.Where(c => c.isDel == false).Count();
                pollTemp.ForEach(c => {
                    if (c.Addr.ToLower() == "13d6")
                    {
                        c.DefaultVal = "01";
                    }
                    else if (c.Addr.ToLower() == "13d8")
                    {
                        c.DefaultVal = "00";

                    }
                    else if (c.Addr.ToLower() == "13d9")
                    {
                        c.DefaultVal = count.ToString("X2");

                    }
                    else if (c.Addr.ToLower() == "125c")
                    {
                        c.DefaultVal = "01";
                    }
                    //else if (c.Addr.ToLower() == "1441")
                    //{
                    //    c.DefaultVal = $"{Convert.ToInt16(cmb_Setting1.EditValue).ToString("x2").PadLeft(2, '0')}";
                    //}
                    else if (c.Addr.ToLower() == "1427")
                    {
                        c.DefaultVal = $"{Convert.ToInt16(cmb_Setting2.EditValue).ToString("x2").PadLeft(2, '0')}";
                    }
                    else if (c.Addr.ToLower() == "1428")
                    {
                        c.DefaultVal = $"{Convert.ToInt16(cmb_Setting3.EditValue).ToString("x2").PadLeft(2, '0')}";
                    }
                    else if (c.Addr.ToLower() == "1412")
                    {
                        c.DefaultVal = checkEdit1.Checked ? "01" : "00";
                    }
                    else if (c.Addr.ToLower() == "1441" && cmb_Polling_Pin_Select.EditValue.ToString() == "ADC_IN")
                    {
                        c.DefaultVal = "03";
                    }


                });
                listC = listC.OrderBy(c => c.Sort).ToList();
                int Offsetvalue = 0;
                for (int i = 0x13da; i < 0x13da+count; i++)
                {
                    pollTemp.ForEach(c =>{
                        if (c.Addr.ToLower() == i.ToString("x"))
                        {
                            //确保是未删除的
                            while (listC[i - 0x13da + Offsetvalue].isDel)
                            {
                                Offsetvalue++;
                            }
                            c.DefaultVal = listC[i- 0x13da + Offsetvalue].tag.ToString("X2");
                        }
                    });
                }
                for (int i = 0x13da + count; i < 0x13da + 48; i++)
                {
                    pollTemp.Remove(pollTemp.Find(c => c.Addr.ToLower() == i.ToString("x2")));
                }
                var str = OutputTextToPolling(pollTemp.OrderBy(c=>c.Addr).ToList());

                if (null != SendPolling)
                {
                    SendPolling(str);
                }
            }
            else
            {
                //ADc

                if (xtraTabControl1.SelectedTabPageIndex == 0)
                {
                    if (cmb_Setting0.EditValue == null || cmb_Setting1.EditValue == null || cmb_Setting2.EditValue == null || cmb_Setting3.EditValue == null)
                    {
                        XtraMessageBox.Show("存在下拉框未选择！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    polllist.ForEach(c => {
                        if (c.Addr.ToLower() == "13d6")
                        {
                            c.DefaultVal = "01";
                        }
                        else if (c.Addr.ToLower() == "13d8")
                        {
                            c.DefaultVal = "02";

                        }
                        else if (c.Addr.ToLower() == "1441")
                        {
                            c.DefaultVal = "01";

                        }
                        else if (c.Addr.ToLower() == "1425")
                        {
                            c.DefaultVal = $"{Convert.ToInt16(cmb_Setting0.EditValue).ToString("x2").PadLeft(2, '0')}";
                        }
                        else if (c.Addr.ToLower() == "1426")
                        {
                            c.DefaultVal = $"{Convert.ToInt16(cmb_Setting1.EditValue).ToString("x2").PadLeft(2, '0')}";
                        }
                        else if (c.Addr.ToLower() == "1427")
                        {
                            c.DefaultVal = $"{Convert.ToInt16(cmb_Setting2.EditValue).ToString("x2").PadLeft(2, '0')}";
                        }
                        else if (c.Addr.ToLower() == "1428")
                        {
                            c.DefaultVal = $"{Convert.ToInt16(cmb_Setting3.EditValue).ToString("x2").PadLeft(2, '0')}";
                        }
                      

                    });

                    //0x1425,0x00,//     [ 7: 0]ASP_State_0_setting_idx; //default:0
                    //0x1426,0x01,//     [ 7: 0]ASP_State_1_setting_idx;//default:1
                    //0x1427,0x02,//     [ 7: 0]ASP_State_2_setting_idx;//default:2
                    //0x1428,0x03,//     [ 7: 0]ASP_State_3_setting_idx;//default:3

                    var plist = polllist.Where(c => c.ADCDial == 1).OrderBy(c => c.Addr).ToList();

                    var str =  OutputTextToPolling(plist);

                    if (null != SendPolling)
                    {
                        SendPolling(str);
                    }
                }
                if (xtraTabControl1.SelectedTabPageIndex == 1)
                {
                    if (cmb_gpoiSetting0.EditValue == null || cmb_gpoiSetting1.EditValue == null || cmb_gpoiSetting2.EditValue == null || cmb_gpoiSetting3.EditValue == null)
                    {
                        XtraMessageBox.Show("存在下拉框未选择！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    polllist.ForEach(c => {
                        if (c.Addr.ToLower() == "13d6")
                        {
                            c.DefaultVal = "01";
                        }
                        else if (c.Addr.ToLower() == "13d8")
                        {
                            c.DefaultVal = "01";

                        }
                        else if (c.Addr.ToLower() == "1425")
                        {
                            c.DefaultVal = $"{Convert.ToInt16(cmb_gpoiSetting0.EditValue).ToString("x2").PadLeft(2, '0')}";
                        }
                        else if (c.Addr.ToLower() == "1426")
                        {
                            c.DefaultVal = $"{Convert.ToInt16(cmb_gpoiSetting1.EditValue).ToString("x2").PadLeft(2, '0')}";
                        }
                        else if (c.Addr.ToLower() == "1427")
                        {
                            c.DefaultVal = $"{Convert.ToInt16(cmb_gpoiSetting2.EditValue).ToString("x2").PadLeft(2, '0')}";
                        }
                        else if (c.Addr.ToLower() == "1428")
                        {
                            c.DefaultVal = $"{Convert.ToInt16(cmb_gpoiSetting3.EditValue).ToString("x2").PadLeft(2, '0')}";
                        }
                        else if (c.Addr.ToLower() == "1443")
                        {
                            c.DefaultVal = Convert.ToUInt32(textEdit2.Text).ToString("X2");
                        }
                        else if (c.Addr.ToLower() == "1444")
                        {
                            c.DefaultVal = Convert.ToUInt32(textEdit1.Text).ToString("X2");
                        }
                       
                    });
                    //0x1425,0x00,//  [ 7: 0]ASP_State_0_setting_idx; //default:0
                    //0x1426,0x01,//  [ 7: 0]ASP_State_1_setting_idx;//default:1
                    //0x1427,0x02,//  [ 7: 0]ASP_State_2_setting_idx;//default:2
                    //0x1428,0x03,//  [ 7: 0]ASP_State_3_setting_idx;//default:3
                    var plist = polllist.Where(c => c.GPIODial == 1).OrderBy(c => c.Addr).ToList();
                    var str = OutputTextToPolling(plist);

                    if (null != SendPolling)
                    {
                        SendPolling(str);
                    }
                }
            }

            DialogResult dr = DevExpress.XtraEditors.XtraMessageBox.Show($"保存成功！\r\n   选择YES后退出窗体！ ", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
            if (dr == DialogResult.Yes)
            {
                this.Close();
            }

        }



        private string OutputTextToPolling(List<polling_register> po)
        {
            //            [ParaList]
            //0xffff,0xfef1,
            //0xfffd,0x20,
            //0xfffe,0x00,

            StringBuilder sb = new StringBuilder();
            //sb.AppendLine("0xffff,0xfef1,");
            string addrP = string.Empty;
            foreach (var item in po)
            {
                if (string.IsNullOrEmpty(addrP))
                {
                    addrP = item.AddrPart;
                    sb.AppendLine($"0xfffd,0x{addrP[0]}{addrP[1]},");
                    sb.AppendLine($"0xfffe,0x{addrP[2]}{addrP[3]},");
                }
                if (addrP != item.AddrPart)
                {
                    sb.AppendLine($"0xfffd,0x{item.AddrPart[0]}{item.AddrPart[1]},");
                    sb.AppendLine($"0xfffe,0x{item.AddrPart[2]}{item.AddrPart[3]},");
                }

                sb.AppendLine($"0x{item.Addr},0x{item.DefaultVal},//{item.Bits} {item.Description}//");

                addrP = item.AddrPart;
            }



            return sb.ToString();


        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            var  buttonId = e.Button.Index;
            var row = gridView1.GetSelectedRows();
            //var id = gridView1.GetRowCellValue(row[0], "Id").ToString();
            //var sort = gridView1.GetRowCellValue(row[0], "Sort").ToString();
            var binName = gridView1.GetRowCellValue(row[0], "BinName").ToString();

            if (buttonId == 0)//向上
            {
                if (listC.First(c => c.BinName == binName).Sort == 0)
                {
                    return;
                }
                int focused = -1;
                if (listC.First(c => c.BinName == binName).Sort - 1 >= 0)
                {
                    listC.First(c => c.Sort == listC.First(t => t.BinName == binName).Sort - 1).Sort += 1;
                    focused = (listC.First(c => c.BinName == binName).Sort -= 1);

                }



                gridControl1.DataSource = listC.Where(c => c.isDel == false).OrderBy(c => c.Sort);
                gridView1.RefreshData();
                //gridView1.SelectRow(focused);
                gridView1.FocusedRowHandle = focused;

                gridView1.SetMasterRowExpanded(focused, true);
                gridView1.Focus();
            }
            else if (buttonId ==1)//向下
            {
                if (listC.First(c => c.BinName == binName).Sort == listC.Where(c => c.isDel == false).Max(c => c.Sort))
                {
                    return;
                }
                int focused = -1;
                if (listC.First(c => c.BinName == binName).Sort + 1 <= listC.Max(c => c.Sort))
                {
                    listC.First(c => c.Sort == listC.First(t => t.BinName == binName).Sort + 1).Sort -= 1;
                    focused = listC.First(c => c.BinName == binName).Sort += 1;
                }
                else
                {
                    focused = listC.Max(c => c.Sort);
                }
                gridControl1.DataSource = listC.Where(c => c.isDel == false).OrderBy(c => c.Sort);
                gridView1.RefreshData();
                gridView1.FocusedRowHandle = focused;
                gridView1.SetMasterRowExpanded(focused, true);
                gridView1.Focus();
            }
            else if (buttonId ==2)//删除
            {
                listC.ForEach(c => {
                    if (c.BinName == binName)
                    {
                        c.isDel = true;
                    }
                });
                this.gridControl1.DataSource = listC.Where(c => c.isDel == false).OrderBy(c => c.Sort);
                this.gridView1.RefreshData();
            }

            
        }

        private void Key_Down_Delay_EditValueChanged(object sender, EventArgs e)
        {
            //0x140c,0x14,//[7:0]Key_Down_Delay;
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "140c")
                {
                    c.DefaultVal = (sender as TextEdit).Text.PadLeft(2, '0');
                }
            });
        }

        private void Key_Up_Delay_EditValueChanged(object sender, EventArgs e)
        {
            //0x140d,0x14,//[7:0]Key_Up_Delay;
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "140d")
                {
                    c.DefaultVal = (sender as TextEdit).Text.PadLeft(2, '0');
                }
            });
        }

        private void Scan_Key_Time_EditValueChanged(object sender, EventArgs e)
        {

            //            0x1664,0x20,//[7:0]Scan_Key_Time;//Buttondelayjitterreductiontime
            //0x1665,0x00,//[15:8]Scan_Key_Time;//Buttondelayjitterreductiontime
            //0x1666,0x00,//[23:16]Scan_Key_Time;//Buttondelayjitterreductiontime
            //0x1667,0x00,//[31:24]Scan_Key_Time;//Buttondelayjitterreductiontime

            var str = (sender as TextEdit).Text.PadLeft(8, '0');
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "1664")
                {
                    c.DefaultVal = $"{str[6]}{str[7]}";
                }
                if (c.Addr.ToLower() == "1665")
                {
                    c.DefaultVal = $"{str[4]}{str[5]}";
                }
                if (c.Addr.ToLower() == "1666")
                {
                    c.DefaultVal = $"{str[2]}{str[3]}";
                }
                if (c.Addr.ToLower() == "1667")
                {
                    c.DefaultVal = $"{str[0]}{str[1]}";
                }
            });
        }

        private void ADC_Value_EditValueChanged(object sender, EventArgs e)
        {
//            0x1418,0x00,//[7:0]Set_ADC_Value;//
//0x1419,0x01,//[15:8]Set_ADC_Value;//
            var str = (sender as TextEdit).Text.PadLeft(4, '0');
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "1418")
                {
                    c.DefaultVal = $"{str[2]}{str[3]}";
                }
                if (c.Addr.ToLower() == "1419")
                {
                    c.DefaultVal = $"{str[0]}{str[1]}";
                }
            });
        }

        private void cmb_Polling_Pin_Select_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmb_Polling_Pin_Select.EditValue.ToString() == "ADC_IN")
            {
                ADC_Value.Enabled = true;
                polllist.ForEach(c => {
                    if (c.Addr.ToLower() == "1441")
                    {
                        c.DefaultVal = $"03";
                    }
                });
            }
            else
            {
                ADC_Value.Enabled = false;

                polllist.ForEach(c => {
                    if (c.Addr.ToLower() == "1411")
                    {
                        c.DefaultVal = $"0b";
                    }
                });
            }


        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkEdit1.Checked)
            {
                Polling_effective.Enabled = true;
            }
            else
            {
                Polling_effective.Enabled = false;
            }
        }

        private void Polling_effective_EditValueChanged(object sender, EventArgs e)
        {
            var str = (sender as TextEdit).Text.PadLeft(4, '0');
            polllist.ForEach(c => {
                if (c.Addr.ToLower() == "1416")
                {
                    c.DefaultVal = $"{str[2]}{str[3]}";
                }
                if (c.Addr.ToLower() == "1417")
                {
                    c.DefaultVal = $"{str[0]}{str[1]}";
                }
            });
        }
    }
}